package com.zjzywl.smoke.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjzywl.smoke.repository.DeviceTypeRepository;
import com.zjzywl.smoke.util.WebResult;
import com.zjzywl.smoke.entity.DeviceType;

@RestController
@RequestMapping(value = "deviceType")
public class DeviceTypeController {

	@Autowired
	private DeviceTypeRepository deviceTypeRepository;

	/*
	 * 获取设备类型列表
	 */
	@RequestMapping(value = "/data/list")
	 
	public WebResult getDeviceTypeData() {
		try {
			List<DeviceType> deviceTypes = this.deviceTypeRepository.findAll();

			return WebResult.OK(deviceTypes);
		} catch (Exception e) {
			// TODO: handle exception
			return WebResult.FAIL(e.getMessage());
		}
	}

	/*
	 * 获取设备类型列表
	 */
	@RequestMapping(value = "/list")
	public String getDeviceTypes(Model model) {
		List<DeviceType> deviceTypes = deviceTypeRepository.findAll();
		model.addAttribute("deviceTypes", deviceTypes);
		return "device/deviceType";
	}

	/*
	 * 保存设备类型
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	 
	public WebResult save(@Valid DeviceType deviceType, BindingResult bindingResult) {
		try {
			DeviceType newDeviceType = null;
			if (deviceType != null) {
				deviceTypeRepository.save(deviceType);
			}
			return WebResult.OK(newDeviceType);
		} catch (Exception e) {
			return WebResult.FAIL(e.getMessage());
		}
	}

	/*
	 * 删除设备类型
	 */
	@RequestMapping(value = "/del/{deviceTypeid}")
	 
	public WebResult delete(@PathVariable("deviceTypeid") Integer deviceTypeid) {
		DeviceType deviceType = deviceTypeRepository.findOne(deviceTypeid);
		try {
			deviceTypeRepository.delete(deviceTypeid);
			return WebResult.OK();
		} catch (Exception e) {
			return WebResult.FAIL(e.getMessage());
		}
	}

	/*
	 * 获取设备类型
	 */
	@RequestMapping(value = "/get/{deviceTypeid}")
	 
	public WebResult get(@PathVariable("deviceTypeid") Integer deviceTypeid) {
		DeviceType deviceType = deviceTypeRepository.findOne(deviceTypeid);
		if (deviceType != null) {
			return WebResult.OK(deviceType);
		} else {
			return WebResult.FAIL("找不到设备类型信息");
		}
	}
}
